package com.yufei.service.index;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.TermVector;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.yufei.utils.CommonUtil;

public class IndexService {
	
	private static int maxNumberHits=4000;
	Analyzer analyzer = new IKAnalyzer();
	 
	Directory directory = null;
	IndexWriter iwriter = null;
	IndexReader ireader = null;
	IndexSearcher isearcher = null;
	private static IndexService indexService =null;
	public static synchronized IndexService getInstance(){
		if(indexService==null){
			indexService=new IndexService();
		}
		return indexService;
	}
	private IndexService() {
		super();
		init();
		// TODO Auto-generated constructor stub
	}
	private void init(){
		try {
			//建立内存索引对象
			directory =  FSDirectory.open(new File(CommonUtil.getVlaue("//indexPath", "indexCf.xml")));	 
			
			//配置IndexWriterConfig
			IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_36 , analyzer);
			iwConfig.setOpenMode(OpenMode.CREATE);
			iwriter = new IndexWriter(directory , iwConfig);
			
		}catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	public void index(Long id,String content) throws Exception{
	if(CommonUtil.isEmptyOrNull(content)||id==null){
		return;
	}
		Document doc = new Document();
		doc.add(new Field("spId", String.valueOf(id), Field.Store.YES, Field.Index.NOT_ANALYZED));
		Field field =new Field("des", content, Field.Store.YES, Field.Index.ANALYZED,TermVector.YES); //new Field(fieldName, text, Field.Store.YES, Field.Index.ANALYZED);
		
		doc.add(field);
		iwriter.addDocument(doc);
		iwriter.commit();
		
	}
	public List<Long> search(String keyword,String field) throws Exception{
		if(ireader==null){
			ireader = IndexReader.open(directory);

		}
		if(isearcher==null){
			isearcher = new IndexSearcher(ireader);		

		}
		List<Long> result=new ArrayList<Long>();
		QueryParser qp = new QueryParser(Version.LUCENE_36, field, analyzer);
		qp.setDefaultOperator(QueryParser.AND_OPERATOR);
		Query query = qp.parse(keyword);
		
		//搜索相似度最高的5条记录
		TopDocs topDocs = isearcher.search(query , maxNumberHits);
	
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		
		for (int i = 0; i < scoreDocs.length; i++){
			Document targetDoc = isearcher.doc(scoreDocs[i].doc);
			try{
			result.add(Long.parseLong(targetDoc.get("spId")));
			}catch(Exception e){
				
			}
		}
		return result;
		
	}
	public int count(String keyword,String field) throws Exception{
		if(ireader==null){
			ireader = IndexReader.open(directory);

		}
		if(isearcher==null){
			isearcher = new IndexSearcher(ireader);		

		}
		QueryParser qp = new QueryParser(Version.LUCENE_36, field, analyzer);
		qp.setDefaultOperator(QueryParser.AND_OPERATOR);
		Query query = qp.parse(keyword);
		
		//搜索相似度最高的5条记录
		TopDocs topDocs = isearcher.search(query , maxNumberHits);
		
		
		return topDocs.totalHits;
		
	}
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
	/*	// TODO Auto-generated method stub
		PfwService pfwService=PfwService.pfwService;
		HashMap parametersMap = new HashMap();
		//parametersMap.put("mallId:=", 2);
		List<Sp> sps=pfwService.query(parametersMap, Sp.class);
		IndexService indexService=IndexService.getInstance();
	for(Sp sp:sps){
		if(sp.getLink().contains("amazon")){
			sp.setMallId(2L);
			try {
				indexService.index(sp);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			pfwService.save(sp);
		}
			
		}*/
		/*int count=indexService.count("清爽", "des");
		System.out.print(count+"\n");
		List<Long> spids=indexService.search("清爽", "des");
		for(Long id:spids){
			Sp sp=pfwService.query("id", id, Sp.class);
			System.out.print(sp.getSpName()+"\n");

		}*/
		
     
	}

}
